// Protocol3 核心管理系统
// 提供协议注册、验证、配置生成、协议绑定等核心功能

import type {
  MerchantChannelConfig3,
  QRCodeConfig,
  DefaultProtocol,
  ProtocolBinding,
  ChannelConfigType,
  ValidationResult,
  PerformanceMetrics,
  CacheStats,
  LogEntry,
  HealthStatus
} from '../types/protocol3-types'
import {
  ProtocolType3,
  ProtocolBindingStatus,
  mergeValidationResults,
  validateFieldValue,
  formatTimestamp,
  deepClone,
  generateProtocolId,
  generateUniqueId
} from '../types/protocol3-types'

// 缓存统计信息
interface CacheEntry {
  data: any
  timestamp: number
  hitCount: number
}

// 性能指标收集器
class PerformanceCollector {
  private resolveCount = 0
  private totalResolveTime = 0
  private errorCount = 0
  private startTime = Date.now()

  recordResolve(duration: number): void {
    this.resolveCount++
    this.totalResolveTime += duration
  }

  recordError(): void {
    this.errorCount++
  }

  getMetrics(): PerformanceMetrics {
    const uptime = Date.now() - this.startTime
    return {
      resolveCount: this.resolveCount,
      averageResolveTime: this.resolveCount > 0 ? this.totalResolveTime / this.resolveCount : 0,
      cacheHitRate: 0, // 将由缓存管理器提供
      errorRate: this.resolveCount > 0 ? this.errorCount / this.resolveCount : 0,
      totalErrors: this.errorCount,
      uptime
    }
  }

  reset(): void {
    this.resolveCount = 0
    this.totalResolveTime = 0
    this.errorCount = 0
    this.startTime = Date.now()
  }
}

// 日志管理器
class LogManager {
  private logs: LogEntry[] = []
  private maxLogs = 1000

  log(level: LogEntry['level'], operation: string, message: string, protocolId?: string, details?: any, duration?: number): void {
    const entry: LogEntry = {
      timestamp: formatTimestamp(Date.now()),
      level,
      operation,
      protocolId,
      message,
      details,
      duration
    }

    this.logs.unshift(entry)

    // 保持日志数量限制
    if (this.logs.length > this.maxLogs) {
      this.logs = this.logs.slice(0, this.maxLogs)
    }

    // 输出到控制台（开发环境）
    if (typeof window !== 'undefined' && (window as any).__DEV__) {
      const logMethod = level === 'ERROR' ? console.error :
                       level === 'WARN' ? console.warn :
                       level === 'DEBUG' ? console.debug : console.log

      logMethod(`[Protocol3Manager] ${level} ${operation}: ${message}`, details || '')
    }
  }

  getLogs(level?: LogEntry['level'], operation?: string): LogEntry[] {
    return this.logs.filter(log => {
      if (level && log.level !== level) return false
      if (operation && log.operation !== operation) return false
      return true
    })
  }

  clearLogs(): void {
    this.logs = []
  }

  getLogCount(): number {
    return this.logs.length
  }
}

// 缓存管理器
class CacheManager {
  private cache = new Map<string, CacheEntry>()
  private maxSize = 100
  private totalHits = 0
  private totalMisses = 0

  get(key: string): any | null {
    const entry = this.cache.get(key)
    if (entry) {
      entry.hitCount++
      this.totalHits++
      return entry.data
    }

    this.totalMisses++
    return null
  }

  set(key: string, data: any): void {
    // LRU eviction
    if (this.cache.size >= this.maxSize) {
      const oldestKey = this.cache.keys().next().value
      if (oldestKey) {
        this.cache.delete(oldestKey)
      }
    }

    this.cache.set(key, {
      data: deepClone(data),
      timestamp: Date.now(),
      hitCount: 0
    })
  }

  has(key: string): boolean {
    return this.cache.has(key)
  }

  delete(key: string): boolean {
    return this.cache.delete(key)
  }

  clear(): void {
    this.cache.clear()
    this.totalHits = 0
    this.totalMisses = 0
  }

  getStats(): CacheStats {
    const total = this.totalHits + this.totalMisses
    return {
      size: this.cache.size,
      hitRate: total > 0 ? this.totalHits / total : 0,
      missRate: total > 0 ? this.totalMisses / total : 0,
      keys: Array.from(this.cache.keys()),
      totalHits: this.totalHits,
      totalMisses: this.totalMisses
    }
  }
}

// Protocol3 核心管理器
export class Protocol3Manager {
  private static instance: Protocol3Manager
  private performanceCollector: PerformanceCollector
  private logManager: LogManager
  private cacheManager: CacheManager

  // 协议存储
  private merchantChannelProtocols = new Map<string, MerchantChannelConfig3>()
  private qrCodeProtocols = new Map<string, QRCodeConfig>()
  private defaultProtocols = new Map<string, DefaultProtocol>()

  // 协议绑定存储
  private protocolBindings = new Map<string, ProtocolBinding>()
  private channelConfigTypes = new Map<string, ChannelConfigType>()

  private constructor() {
    this.performanceCollector = new PerformanceCollector()
    this.logManager = new LogManager()
    this.cacheManager = new CacheManager()

    this.initializeChannelConfigTypes()
    this.logManager.log('INFO', 'INIT', 'Protocol3Manager initialized')
  }

  public static getInstance(): Protocol3Manager {
    if (!Protocol3Manager.instance) {
      Protocol3Manager.instance = new Protocol3Manager()
    }
    return Protocol3Manager.instance
  }

  // 初始化渠道配置类型
  private initializeChannelConfigTypes(): void {
    const configTypes: ChannelConfigType[] = [
      {
        configType: 'MERCHANT_CONFIG',
        configName: '商户配置',
        channelCode: 'WXPAY',
        channelName: '微信支付',
        description: '微信支付商户配置',
        enabled: true
      },
      {
        configType: 'QR_CODE_CONFIG',
        configName: '二维码配置',
        channelCode: 'WXPAY',
        channelName: '微信支付',
        description: '微信支付二维码配置',
        enabled: true
      },
      {
        configType: 'MERCHANT_CONFIG',
        configName: '商户配置',
        channelCode: 'ALIPAY',
        channelName: '支付宝',
        description: '支付宝商户配置',
        enabled: true
      },
      {
        configType: 'QR_CODE_CONFIG',
        configName: '二维码配置',
        channelCode: 'ALIPAY',
        channelName: '支付宝',
        description: '支付宝二维码配置',
        enabled: true
      }
    ]

    configTypes.forEach(config => {
      const key = `${config.channelCode}:${config.configType}`
      this.channelConfigTypes.set(key, config)
    })
  }

  // ==================== 协议查找 ====================

  /**
   * 根据协议代码和商户配置类型按约定查找协议
   * @param protocolCode 协议代码，例如 'CHANNEL_PROTOCOL_WXPAY'
   * @param configType 商户配置类型，例如 'PROVIDER', 'DIRECT_MERCHANT', 'SUB_MERCHANT'
   * @returns 协议配置，如果没有找到则返回默认兜底协议ID
   */
  public getProtocolByConvention(protocolCode: string, configType: string): string {
    const startTime = Date.now()

    try {
      // 将协议代码转换为渠道代码
      // CHANNEL_PROTOCOL_WXPAY -> WXPAY
      const channelCode = protocolCode.replace('CHANNEL_PROTOCOL_', '')

      // 根据约定生成协议ID: PROTOCOL3_{CHANNEL}_{CONFIG_TYPE}
      const conventionProtocolId = `PROTOCOL3_${channelCode}_${configType}`

      this.logManager.log('DEBUG', 'GET_PROTOCOL_BY_CONVENTION',
        `查找协议: ${protocolCode} + ${configType} -> ${conventionProtocolId}`)

      // 查找协议
      const protocol = this.getProtocol(conventionProtocolId)

      if (protocol) {
        const duration = Date.now() - startTime
        this.performanceCollector.recordResolve(duration)
        this.logManager.log('INFO', 'GET_PROTOCOL_BY_CONVENTION',
          `按约定找到协议: ${conventionProtocolId}`, conventionProtocolId, null, duration)
        return conventionProtocolId
      } else {
        // 如果没有找到约定的协议，返回默认兜底协议
        const fallbackProtocolId = 'DEFAULT_PROTOCOL_FALLBACK_001'
        const duration = Date.now() - startTime
        this.performanceCollector.recordResolve(duration)
        this.logManager.log('WARN', 'GET_PROTOCOL_BY_CONVENTION',
          `未找到约定协议 ${conventionProtocolId}，返回兜底协议: ${fallbackProtocolId}`,
          conventionProtocolId, { originalCode: protocolCode, configType }, duration)
        return fallbackProtocolId
      }

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'GET_PROTOCOL_BY_CONVENTION',
        `按约定查找协议失败: ${errorMessage}`, undefined,
        { protocolCode, configType, error })

      // 发生错误时也返回兜底协议
      return 'DEFAULT_PROTOCOL_FALLBACK_001'
    }
  }

  // ==================== 协议管理 ====================

  /**
   * 注册商户渠道配置协议
   */
  public registerMerchantChannelConfig(config: MerchantChannelConfig3): void {
    const startTime = Date.now()

    try {
      // 验证协议配置
      const validation = this.validateMerchantChannelConfig(config)
      if (!validation.valid) {
        throw new Error(`协议配置验证失败: ${validation.errors.join(', ')}`)
      }

      // 注册协议
      this.merchantChannelProtocols.set(config.protocolId, config)

      // 清除相关缓存
      this.invalidateCache(config.protocolId)

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('INFO', 'REGISTER_MERCHANT_CHANNEL', `商户渠道协议注册成功: ${config.name}`, config.protocolId, null, duration)

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'REGISTER_MERCHANT_CHANNEL', `商户渠道协议注册失败: ${errorMessage}`, config.protocolId, error)
      throw error
    }
  }

  /**
   * 注册二维码配置协议
   */
  public registerQRCodeConfig(config: QRCodeConfig): void {
    const startTime = Date.now()

    try {
      // 验证协议配置
      const validation = this.validateQRCodeConfig(config)
      if (!validation.valid) {
        throw new Error(`协议配置验证失败: ${validation.errors.join(', ')}`)
      }

      // 注册协议
      this.qrCodeProtocols.set(config.protocolId, config)

      // 清除相关缓存
      this.invalidateCache(config.protocolId)

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('INFO', 'REGISTER_QR_CODE', `二维码协议注册成功: ${config.name}`, config.protocolId, null, duration)

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'REGISTER_QR_CODE', `二维码协议注册失败: ${errorMessage}`, config.protocolId, error)
      throw error
    }
  }

  /**
   * 注册默认协议
   */
  public registerDefaultProtocol(config: DefaultProtocol): void {
    const startTime = Date.now()

    try {
      // 验证协议配置
      const validation = this.validateDefaultProtocol(config)
      if (!validation.valid) {
        throw new Error(`默认协议配置验证失败: ${validation.errors.join(', ')}`)
      }

      // 注册协议
      this.defaultProtocols.set(config.protocolId, config)

      // 清除相关缓存
      this.invalidateCache(config.protocolId)

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('INFO', 'REGISTER_DEFAULT', `默认协议注册成功: ${config.name}`, config.protocolId, null, duration)

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'REGISTER_DEFAULT', `默认协议注册失败: ${errorMessage}`, config.protocolId, error)
      throw error
    }
  }

  /**
   * 注销协议配置
   */
  public unregisterProtocol(protocolId: string): void {
    const startTime = Date.now()

    try {
      const removed = this.merchantChannelProtocols.delete(protocolId) ||
                     this.qrCodeProtocols.delete(protocolId) ||
                     this.defaultProtocols.delete(protocolId)

      if (removed) {
        // 删除相关的协议绑定
        this.removeProtocolBindings(protocolId)
        this.invalidateCache(protocolId)

        const duration = Date.now() - startTime
        this.logManager.log('INFO', 'UNREGISTER', `协议注销成功`, protocolId, null, duration)
      } else {
        this.logManager.log('WARN', 'UNREGISTER', `协议不存在`, protocolId)
      }

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'UNREGISTER', `协议注销失败: ${errorMessage}`, protocolId, error)
      throw error
    }
  }

  /**
   * 获取协议配置
   */
  public getProtocol(protocolId: string): MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol | null {
    const startTime = Date.now()

    try {
      // 尝试从缓存获取
      const cacheKey = `protocol:${protocolId}`
      let protocol = this.cacheManager.get(cacheKey)

      if (!protocol) {
        protocol = this.merchantChannelProtocols.get(protocolId) ||
                  this.qrCodeProtocols.get(protocolId) ||
                  this.defaultProtocols.get(protocolId)

        if (protocol) {
          this.cacheManager.set(cacheKey, protocol)
        }
      }

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)

      if (protocol) {
        this.logManager.log('DEBUG', 'GET_PROTOCOL', `获取协议成功`, protocolId, null, duration)
      } else {
        this.logManager.log('WARN', 'GET_PROTOCOL', `协议不存在`, protocolId, null, duration)
      }

      return protocol

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'GET_PROTOCOL', `获取协议失败: ${errorMessage}`, protocolId, error)
      return null
    }
  }

  /**
   * 获取所有商户渠道配置协议
   */
  public getAllMerchantChannelConfigs(): MerchantChannelConfig3[] {
    return Array.from(this.merchantChannelProtocols.values())
  }

  /**
   * 获取所有二维码配置协议
   */
  public getAllQRCodeConfigs(): QRCodeConfig[] {
    return Array.from(this.qrCodeProtocols.values())
  }

  /**
   * 获取所有默认协议
   */
  public getAllDefaultProtocols(): DefaultProtocol[] {
    return Array.from(this.defaultProtocols.values())
  }

  /**
   * 获取所有协议配置
   */
  public getAllProtocols(): (MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol)[] {
    return [...this.getAllMerchantChannelConfigs(), ...this.getAllQRCodeConfigs(), ...this.getAllDefaultProtocols()]
  }

  // ==================== 协议绑定管理 ====================

  /**
   * 创建协议绑定
   */
  public createProtocolBinding(binding: Omit<ProtocolBinding, 'bindingId' | 'createTime' | 'updateTime'>): ProtocolBinding {
    const startTime = Date.now()

    try {
      // 验证协议是否存在
      const protocol = this.getProtocol(binding.protocolId)
      if (!protocol) {
        throw new Error(`协议不存在: ${binding.protocolId}`)
      }

      // 验证渠道配置类型是否存在
      const configTypeKey = `${binding.channelCode}:${binding.configType}`
      if (!this.channelConfigTypes.has(configTypeKey)) {
        throw new Error(`渠道配置类型不存在: ${configTypeKey}`)
      }

      const newBinding: ProtocolBinding = {
        ...binding,
        bindingId: generateUniqueId('binding'),
        createTime: formatTimestamp(Date.now()),
        updateTime: formatTimestamp(Date.now())
      }

      this.protocolBindings.set(newBinding.bindingId, newBinding)

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('INFO', 'CREATE_BINDING', `协议绑定创建成功`, binding.protocolId, newBinding, duration)

      return newBinding

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'CREATE_BINDING', `协议绑定创建失败: ${errorMessage}`, binding.protocolId, error)
      throw error
    }
  }

  /**
   * 更新协议绑定
   */
  public updateProtocolBinding(bindingId: string, updates: Partial<ProtocolBinding>): ProtocolBinding {
    const startTime = Date.now()

    try {
      const existingBinding = this.protocolBindings.get(bindingId)
      if (!existingBinding) {
        throw new Error(`协议绑定不存在: ${bindingId}`)
      }

      const updatedBinding: ProtocolBinding = {
        ...existingBinding,
        ...updates,
        bindingId, // 确保ID不被修改
        updateTime: formatTimestamp(Date.now())
      }

      this.protocolBindings.set(bindingId, updatedBinding)

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('INFO', 'UPDATE_BINDING', `协议绑定更新成功`, existingBinding.protocolId, updatedBinding, duration)

      return updatedBinding

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'UPDATE_BINDING', `协议绑定更新失败: ${errorMessage}`, undefined, error)
      throw error
    }
  }

  /**
   * 删除协议绑定
   */
  public deleteProtocolBinding(bindingId: string): boolean {
    const startTime = Date.now()

    try {
      const binding = this.protocolBindings.get(bindingId)
      const removed = this.protocolBindings.delete(bindingId)

      if (removed && binding) {
        const duration = Date.now() - startTime
        this.logManager.log('INFO', 'DELETE_BINDING', `协议绑定删除成功`, binding.protocolId, null, duration)
      } else {
        this.logManager.log('WARN', 'DELETE_BINDING', `协议绑定不存在`, undefined)
      }

      return removed

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'DELETE_BINDING', `协议绑定删除失败: ${errorMessage}`, undefined, error)
      throw error
    }
  }

  /**
   * 获取协议的所有绑定
   */
  public getProtocolBindings(protocolId: string): ProtocolBinding[] {
    return Array.from(this.protocolBindings.values())
      .filter(binding => binding.protocolId === protocolId)
      .sort((a, b) => a.priority - b.priority)
  }

  /**
   * 获取渠道配置类型的绑定
   */
  public getChannelConfigBindings(channelCode: string, configType: string): ProtocolBinding[] {
    return Array.from(this.protocolBindings.values())
      .filter(binding => binding.channelCode === channelCode && binding.configType === configType)
      .sort((a, b) => a.priority - b.priority)
  }

  /**
   * 获取所有协议绑定
   */
  public getAllProtocolBindings(): ProtocolBinding[] {
    return Array.from(this.protocolBindings.values())
  }

  // ==================== 渠道配置类型管理 ====================

  /**
   * 获取渠道配置类型
   */
  public getChannelConfigTypes(channelCode?: string): ChannelConfigType[] {
    const types = Array.from(this.channelConfigTypes.values())

    if (channelCode) {
      return types.filter(type => type.channelCode === channelCode)
    }

    return types
  }

  /**
   * 添加渠道配置类型
   */
  public addChannelConfigType(configType: ChannelConfigType): void {
    const key = `${configType.channelCode}:${configType.configType}`
    this.channelConfigTypes.set(key, configType)

    this.logManager.log('INFO', 'ADD_CONFIG_TYPE', `渠道配置类型添加成功: ${key}`)
  }

  // ==================== 配置操作 ====================

  /**
   * 生成默认配置
   */
  public generateDefaultConfig(protocolId: string): Record<string, any> {
    const startTime = Date.now()

    try {
      const cacheKey = `default_config:${protocolId}`
      let defaultConfig = this.cacheManager.get(cacheKey)

      if (!defaultConfig) {
        const protocol = this.getProtocol(protocolId)
        if (protocol) {
          defaultConfig = this.generateConfigFromProtocol(protocol)
          this.cacheManager.set(cacheKey, defaultConfig)
        } else {
          defaultConfig = {}
        }
      }

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)
      this.logManager.log('DEBUG', 'GENERATE_DEFAULT', `生成默认配置成功`, protocolId, null, duration)

      return defaultConfig

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'GENERATE_DEFAULT', `生成默认配置失败: ${errorMessage}`, protocolId, error)
      return {}
    }
  }

  /**
   * 验证配置数据
   */
  public validateConfig(protocolId: string, configData: Record<string, any>): ValidationResult {
    const startTime = Date.now()

    try {
      const protocol = this.getProtocol(protocolId)
      let result: ValidationResult

      if (protocol) {
        result = this.validateConfigWithProtocol(protocol, configData)
      } else {
        result = {
          valid: false,
          errors: [`协议不存在: ${protocolId}`]
        }
      }

      const duration = Date.now() - startTime
      this.performanceCollector.recordResolve(duration)

      const level = result.valid ? 'DEBUG' : 'WARN'
      this.logManager.log(level, 'VALIDATE_CONFIG', `配置验证${result.valid ? '成功' : '失败'}`, protocolId, result, duration)

      return result

    } catch (error) {
      this.performanceCollector.recordError()
      const errorMessage = error instanceof Error ? error.message : String(error)
      this.logManager.log('ERROR', 'VALIDATE_CONFIG', `配置验证异常: ${errorMessage}`, protocolId, error)

      return {
        valid: false,
        errors: [`配置验证异常: ${errorMessage}`]
      }
    }
  }

  // ==================== 系统管理 ====================

  /**
   * 清除缓存
   */
  public clearCache(): void {
    this.cacheManager.clear()
    this.logManager.log('INFO', 'CLEAR_CACHE', '缓存已清除')
  }

  /**
   * 获取缓存统计
   */
  public getCacheStats(): CacheStats {
    return this.cacheManager.getStats()
  }

  /**
   * 获取性能指标
   */
  public getMetrics(): PerformanceMetrics {
    const metrics = this.performanceCollector.getMetrics()
    const cacheStats = this.getCacheStats()

    return {
      ...metrics,
      cacheHitRate: cacheStats.hitRate
    }
  }

  /**
   * 获取日志
   */
  public getLogs(level?: LogEntry['level'], operation?: string): LogEntry[] {
    return this.logManager.getLogs(level, operation)
  }

  /**
   * 清除日志
   */
  public clearLogs(): void {
    this.logManager.clearLogs()
  }

  /**
   * 获取系统健康状态
   */
  public getHealthStatus(): HealthStatus {
    const checks = []

    // 检查协议注册表
    const totalProtocols = this.getAllProtocols().length
    checks.push({
      name: 'protocol_registry',
      status: totalProtocols > 0 ? 'pass' : 'warn' as const,
      message: `已注册 ${totalProtocols} 个协议配置`,
      details: { totalProtocols }
    })

    // 检查协议绑定
    const totalBindings = this.getAllProtocolBindings().length
    checks.push({
      name: 'protocol_bindings',
      status: 'pass' as const,
      message: `已创建 ${totalBindings} 个协议绑定`,
      details: { totalBindings }
    })

    // 检查缓存状态
    const cacheStats = this.getCacheStats()
    checks.push({
      name: 'cache_system',
      status: 'pass' as const,
      message: `缓存命中率: ${(cacheStats.hitRate * 100).toFixed(1)}%`,
      details: cacheStats
    })

    // 检查性能指标
    const metrics = this.getMetrics()
    checks.push({
      name: 'performance',
      status: metrics.errorRate < 0.1 ? 'pass' : 'warn' as const,
      message: `错误率: ${(metrics.errorRate * 100).toFixed(1)}%`,
      details: metrics
    })

    const overallStatus = checks.some(c => c.status === 'fail') ? 'unhealthy' :
                         checks.some(c => c.status === 'warn') ? 'degraded' : 'healthy'

    return {
      status: overallStatus,
      checks,
      timestamp: formatTimestamp(Date.now())
    }
  }

  // ==================== 私有方法 ====================

  /**
   * 验证商户渠道配置协议
   */
  private validateMerchantChannelConfig(config: MerchantChannelConfig3): ValidationResult {
    const results: ValidationResult[] = []

    // 基本字段验证
    if (!config.protocolId) {
      results.push({ valid: false, errors: ['协议ID不能为空'] })
    }

    if (!config.name) {
      results.push({ valid: false, errors: ['协议名称不能为空'] })
    }

    if (config.protocolType !== ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3) {
      results.push({ valid: false, errors: ['协议类型必须为MERCHANT_CHANNEL_CONFIG_V3'] })
    }

    // 配置段验证
    if (!config.configSections || config.configSections.length === 0) {
      results.push({ valid: false, errors: ['协议必须包含至少一个配置段'] })
    }

    return mergeValidationResults(results)
  }

  /**
   * 验证二维码配置协议
   */
  private validateQRCodeConfig(config: QRCodeConfig): ValidationResult {
    const results: ValidationResult[] = []

    // 基本字段验证
    if (!config.protocolId) {
      results.push({ valid: false, errors: ['协议ID不能为空'] })
    }

    if (!config.name) {
      results.push({ valid: false, errors: ['协议名称不能为空'] })
    }

    if (config.protocolType !== ProtocolType3.QR_CODE_CONFIG) {
      results.push({ valid: false, errors: ['协议类型必须为QR_CODE_CONFIG'] })
    }

    if (!['STATIC', 'DYNAMIC'].includes(config.codeType)) {
      results.push({ valid: false, errors: ['二维码类型必须为STATIC或DYNAMIC'] })
    }

    return mergeValidationResults(results)
  }

  /**
   * 验证默认协议
   */
  private validateDefaultProtocol(config: DefaultProtocol): ValidationResult {
    const results: ValidationResult[] = []

    // 基本字段验证
    if (!config.protocolId) {
      results.push({ valid: false, errors: ['协议ID不能为空'] })
    }

    if (!config.name) {
      results.push({ valid: false, errors: ['协议名称不能为空'] })
    }

    if (config.protocolType !== ProtocolType3.DEFAULT_PROTOCOL) {
      results.push({ valid: false, errors: ['协议类型必须为DEFAULT_PROTOCOL'] })
    }

    if (typeof config.priority !== 'number' || config.priority < 0) {
      results.push({ valid: false, errors: ['优先级必须为非负数'] })
    }

    if (!config.fallbackConfig || typeof config.fallbackConfig !== 'object') {
      results.push({ valid: false, errors: ['必须提供兜底配置'] })
    }

    // 配置段验证
    if (!config.configSections || config.configSections.length === 0) {
      results.push({ valid: false, errors: ['协议必须包含至少一个配置段'] })
    }

    return mergeValidationResults(results)
  }

  /**
   * 从协议生成配置
   */
  private generateConfigFromProtocol(protocol: MerchantChannelConfig3 | QRCodeConfig | DefaultProtocol): Record<string, any> {
    const config: Record<string, any> = {}

    for (const section of protocol.configSections) {
      for (const field of section.fields) {
        config[field.fieldKey] = field.defaultValue
      }
    }

    return config
  }

  /**
   * 使用协议验证配置
   */
  private validateConfigWithProtocol(protocol: MerchantChannelConfig3 | QRCodeConfig, configData: Record<string, any>): ValidationResult {
    const results: ValidationResult[] = []

    for (const section of protocol.configSections) {
      for (const field of section.fields) {
        const value = configData[field.fieldKey]
        const fieldResult = validateFieldValue(field, value)

        if (!fieldResult.valid) {
          results.push({
            valid: false,
            errors: [fieldResult.error || `字段${field.fieldName}验证失败`]
          })
        }
      }
    }

    return mergeValidationResults(results)
  }

  /**
   * 删除协议相关的绑定
   */
  private removeProtocolBindings(protocolId: string): void {
    const bindingsToRemove = Array.from(this.protocolBindings.entries())
      .filter(([_, binding]) => binding.protocolId === protocolId)
      .map(([id, _]) => id)

    bindingsToRemove.forEach(id => this.protocolBindings.delete(id))

    if (bindingsToRemove.length > 0) {
      this.logManager.log('INFO', 'REMOVE_BINDINGS', `删除协议绑定 ${bindingsToRemove.length} 个`, protocolId)
    }
  }

  /**
   * 使缓存失效
   */
  private invalidateCache(protocolId: string): void {
    // 删除相关的缓存条目
    const keysToDelete = this.cacheManager.getStats().keys.filter(key =>
      key.includes(protocolId)
    )

    for (const key of keysToDelete) {
      this.cacheManager.delete(key)
    }
  }
}

// 导出单例实例
export const protocol3Manager = Protocol3Manager.getInstance()

// 便捷函数
export function registerProtocol3MerchantChannel(config: MerchantChannelConfig3): void {
  protocol3Manager.registerMerchantChannelConfig(config)
}

export function registerProtocol3QRCode(config: QRCodeConfig): void {
  protocol3Manager.registerQRCodeConfig(config)
}

export function getProtocol3Config(protocolId: string): MerchantChannelConfig3 | QRCodeConfig | null {
  return protocol3Manager.getProtocol(protocolId)
}

export function generateProtocol3DefaultConfig(protocolId: string): Record<string, any> {
  return protocol3Manager.generateDefaultConfig(protocolId)
}

export function validateProtocol3Config(protocolId: string, configData: Record<string, any>): ValidationResult {
  return protocol3Manager.validateConfig(protocolId, configData)
}

export function createProtocol3Binding(binding: Omit<ProtocolBinding, 'bindingId' | 'createTime' | 'updateTime'>): ProtocolBinding {
  return protocol3Manager.createProtocolBinding(binding)
}

export function getProtocol3Metrics(): PerformanceMetrics {
  return protocol3Manager.getMetrics()
}

export function getProtocol3HealthStatus(): HealthStatus {
  return protocol3Manager.getHealthStatus()
}

export function getProtocol3ByConvention(protocolCode: string, configType: string): string {
  return protocol3Manager.getProtocolByConvention(protocolCode, configType)
}

// 默认导出
export default {
  Protocol3Manager,
  protocol3Manager,
  registerProtocol3MerchantChannel,
  registerProtocol3QRCode,
  getProtocol3Config,
  generateProtocol3DefaultConfig,
  validateProtocol3Config,
  createProtocol3Binding,
  getProtocol3Metrics,
  getProtocol3HealthStatus,
  getProtocol3ByConvention
}

// 在文件末尾添加进件协议的初始化
// 注意：在实际应用中，这部分应该在协议初始化模块中调用
// 这里为了方便演示放在管理器文件末尾
import { protocol3OnboardingConfigs } from './protocol3-mc-onboarding'

// 自动注册进件协议配置
if (typeof window !== 'undefined') {
  // 确保在浏览器环境中才执行
  setTimeout(() => {
    try {
      protocol3OnboardingConfigs.forEach(config => {
        protocol3Manager.registerMerchantChannelConfig(config)
      })
      console.log('进件协议配置已自动注册', protocol3OnboardingConfigs.length, '个协议')
    } catch (error) {
      console.error('进件协议配置注册失败:', error)
    }
  }, 100)
}